/**************************************************************************
 *
 *   Copyright 2010 American Public Media Group
 *
 *   This file is part of AIR2.
 *
 *   AIR2 is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   AIR2 is distributed in the hope that it will be useful, 
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License 
 *   along with AIR2.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/

Ext.ns('AIR2.Search.Inquiry');

// global cache
AIR2.Search.Inquiry.CACHE = {};

AIR2.Search.Inquiry.addToCache = function(inqs) {
    var C = AIR2.Search.Inquiry.CACHE;
    Ext.each(inqs, function(item, idx, array) {
        // each inq has array of questions with sequence numbers
        C[item.inq_uuid] = {title:item.inq_title, questions:[]};
        Logger("added to inquiry cache: " + item.inq_uuid);
        Ext.each(item.ques_seq_value, function(qsv,idx2,array2) {
            var m = qsv.match(/^(\d+):(.+)/);
            C[item.inq_uuid]['questions'][parseInt(m[1])] = m[2];
        })
    });
}

AIR2.Search.Inquiry.ChainedPicker = function(pickerPanel) {

    var projectStore = new Ext.data.JsonStore({
        url: AIR2.HOMEURL + '/project.json?sort=prj_display_name',
        storeId: 'projectStore',
        restful: true,
        remoteSort: true
    });

    var projectTpl = new Ext.XTemplate(
        '<tpl for=".">',
          '<div class="{[ xindex % 2 ? "alt" : "" ]} picker-item project">{prj_display_name}</div>',
        '</tpl>'
    );

    var pickProject = function(list) {
        var v = list.getValue();
        var rec = projectStore.getById(v);
        Logger("project changed: ", v, rec);
        // add a new combobox for selecting an inquiry 
        var iP = AIR2.Search.Inquiry.InquiryPicker(v,pickerPanel);
        pickerPanel.setInquiryPicker(iP);
        pickerPanel.doLayout();
        pickerPanel.setProjectQuery(rec.get('prj_name'));
        pickerPanel.clause.updateDisplay();
    };

    var projectList = new AIR2.Search.Inquiry.PickerBox({
        width : 700,
        store : projectStore,
        mode  : 'remote',
        cls   : 'adv-search-list',
        border: false,
        forceSelection: true,
        triggerAction: 'all',
        selectOnFocus: true,
        fieldLabel: 'Project',
        emptyText: 'Select a Project',
        loadingText: 'Getting list of Projects...',
        valueField: 'prj_uuid',
        displayField: 'prj_display_name',
        tpl: projectTpl,
        listeners : {
            'select' : pickProject
        },
        removeFromParent : function() {
            Logger("remove this picker");
            pickerPanel.resetProjectPicker();
            pickerPanel.updateDisplay();
        }
    });

    return projectList; 
}

AIR2.Search.Inquiry.InquiryPicker = function(prj_uuid,pickerPanel) {

    var inqStore = new Ext.data.JsonStore({
        url     : AIR2.HOMEURL +'/project/'+prj_uuid+'/inquiries.json?sort=inq_title',
        storeId : 'inquiryStore',
        restful : true,
        remoteSort: true  // IMPORTANT!
    });

    var iP = new AIR2.Search.Inquiry.PickerBox({
        store:          inqStore,
        emptyText:      'Select a Query',
        fieldLabel:     'Query',
        border:         false,
        width:          700,
        forceSelection: true,
        triggerAction:  'all',
        displayField:   'Inquiry:inq_ext_title',
        valueField:     'Inquiry:inq_uuid',
        wrapFocusClass: 'picker-wrapper',
        loadingText:    'Getting list of Queries...',
        //itemSelector:   'div.inq',
        selectOnFocus: true,
        tpl : new Ext.XTemplate(
            '<tpl for="."><div class="{[ xindex % 2 ? "alt" : "" ]} picker-item inq">',
             '<span class="inq_ext_title">{[values["Inquiry:inq_ext_title"]]}</span> ',
             '<span class="inq_title">({[values["Inquiry:inq_title"]]})</span>',
            '</div></tpl>',
            {
                compiled: true, 
                disableFormats: true
            }
        ),
        listeners: {
            'select' : function(thisBox,ev) {
                var v = thisBox.getValue();
                Logger("Picked a Query", v);
                var qP = AIR2.Search.Inquiry.QuestionPicker(v,pickerPanel);
                pickerPanel.setQuestionPicker(qP);
                pickerPanel.doLayout();
                pickerPanel.setInquiryQuery(v);
                pickerPanel.clause.updateDisplay();
            }
        },
        removeFromParent : function() {
            Logger("remove this picker");
            pickerPanel.resetInquiryPicker();
            pickerPanel.updateDisplay();
        }
    });

    return iP;
}

AIR2.Search.Inquiry.QuestionPicker = function(inq_uuid,pickerPanel) {
    var quesStore = new Ext.data.JsonStore({
        url         : AIR2.HOMEURL +'/inquiry/'+inq_uuid+'/questions.json?sort=ques_dis_seq',
        storeId     : 'quesStore',
        restful     : true, 
        remoteSort  : true
    });
    var qP = new AIR2.Search.Inquiry.PickerBox({
        store: quesStore,
        emptyText: 'Select a Question',
        fieldLabel: 'Question',
        border: false,
        width: 700,
        forceSelection: true,
        triggerAction: 'all',
        displayField: 'ques_value', 
        valueField: 'ques_uuid',
        loadingText: 'Getting questions...',
        selectOnFocus: true,
        tpl : new Ext.XTemplate(
            '<tpl for="."><div class="{[ xindex % 2 ? "alt" : "" ]} picker-item question">',
             '<span>{ques_value}</span>',
            '</div></tpl>'
        ),      
        listeners: {
            'select' : function(cbox,ev) {
                var v = cbox.getValue();
                Logger("Picked a question:", v);
                var rec   = quesStore.getById(v);
                Logger(rec);
                var ques_choices = rec.get('ques_choices');
                var aP; 
                if (ques_choices) {
                    aP = AIR2.Search.Inquiry.AnswerPicker(ques_choices,pickerPanel);
                }       
                else {  
                    aP = AIR2.Search.Inquiry.AnswerFullText(rec,pickerPanel);
                }       
                pickerPanel.setAnswerPicker(aP);
                pickerPanel.doLayout();
                pickerPanel.setQuestionQuery(rec.get('ques_uuid'));
                pickerPanel.clause.updateDisplay();
            }       
        },      
        removeFromParent : function() {
            //Logger("remove question picker");
            pickerPanel.resetQuestionPicker();
            pickerPanel.updateDisplay();
        }       
    });

    return qP;
}

AIR2.Search.Inquiry.AnswerPicker = function(values, pickerPanel) {
    //Logger("values:", values);
    var choices = Ext.decode(values);
    //Logger("choices:", choices);
    var defaultVal;
    var opts = [];
    Ext.each(choices, function(item,idx,arr) {
        if (item.isdefault) {
            defaultVal = item.value;
        }
        opts.push(item.value);
    });
    var label = values.length ? 'Select an Answer' : 'Enter an answer';
    var vP = new AIR2.Search.Inquiry.PickerBox({
        store: opts,
        emptyText: label,
        fieldLabel: 'Answer',
        border: false,
        width: 700,
        value: defaultVal,
        forceSelection: false,  // allow free-form entry
        triggerAction: 'all',
        selectOnFocus: true,
        tpl : new Ext.XTemplate(
            '<tpl for="."><div class="{[ xindex % 2 ? "alt" : "" ]} picker-item answer">',
             '<span>{field1}</span>',
            '</div></tpl>'
        ),
        listeners: {
            'select' : function(vbox,ev) {
                var v = vbox.getValue();
                Logger("Picked an answer:", v);
                pickerPanel.setAnswerQuery(v);
                pickerPanel.clause.updateDisplay();
            },
            'keyup' : function(vbox, ev) {
                var v = vbox.getRawValue();
                Logger("entered answer:", v);   // TODO this is broken
                pickerPanel.setAnswerQuery(v);
                pickerPanel.updateDisplay();
            }
        },
        removeFromParent : function() {
            //Logger("remove question picker");
            pickerPanel.resetAnswerPicker();
            pickerPanel.updateDisplay();
        }
    });
    return vP;
}

AIR2.Search.Inquiry.AnswerFullText = function(rec,pickerPanel) {
    
    var store = new AIR2.Search.JsonStore({
        idx: 'responses',
        baseParams: {
            'i' : 'responses'
        },
        listeners:      {
            load: function(thisStore, records, thisOptions) {
                thisStore.isInProcess = false;
                //Logger(thisOptions);
                pickerPanel.setAnswerFullTextQuery(thisOptions.params.q);
                pickerPanel.clause.updateDisplay();
            }
        }
    });
    
    var aft = new Ext.form.ComboBox({
        store           : store,
        triggerClass    :'x-form-clear-trigger',
        minChars        : 2, // one-char queries return too many hits
        enableKeyEvents : true,
        mode            : 'remote',
        queryParam      : 'q',
        queryDelay      : 300, // milliseconds between typing stop and server request.
        width           : 700,
        border          : false,
        fieldLabel      : 'Answer',
        displayField    : '',
        onTriggerClick  : function() {
            //Logger('triggerClick');
            pickerPanel.resetAnswerPicker();
            pickerPanel.updateDisplay();
        },
        listeners       : {
            'beforequery'   : function(queryEvent) {
                //Logger(queryEvent.query);
                var q = queryEvent.query;
                //queryEvent.query = 'answer=('+q+')';
                Logger(queryEvent.query);
            }
        }
    
    });
    
    return aft;
}


AIR2.Search.Inquiry.PickerBox = Ext.extend(Ext.form.ComboBox, {

    initComponent : function(){
        AIR2.Search.Inquiry.PickerBox.superclass.initComponent.call(this);

        this.triggerConfig = {
            tag:'span', cls:'x-form-twin-triggers', cn:[
            {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
            {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
        ]};
    },

    trigger2Class:'x-form-clear-trigger',
    
    listClass:      'picker-box',
    itemSelector:   'div.picker-item',
    selectedClass:  'picker-item-selected',
    
    getTrigger : function(index){
        return this.triggers[index];
    },

    initTrigger : function(){
        var ts = this.trigger.select('.x-form-trigger', true);
        var triggerField = this;
        ts.each(function(t, all, index){
            var triggerIndex = 'Trigger'+(index+1);
            t.hide = function(){
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = 'none';
                triggerField.el.setWidth(w-triggerField.trigger.getWidth());
                this['hidden' + triggerIndex] = true;
            };
            t.show = function(){
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = '';
                triggerField.el.setWidth(w-triggerField.trigger.getWidth());
                this['hidden' + triggerIndex] = false;
            };

            if(this['hide'+triggerIndex]){
                t.dom.style.display = 'none';
                this['hidden' + triggerIndex] = true;
            }
            this.mon(t, 'click', this['on'+triggerIndex+'Click'], this, {preventDefault:true});
            t.addClassOnOver('x-form-trigger-over');
            t.addClassOnClick('x-form-trigger-click');
        }, this);
        this.triggers = ts.elements;
    },

    getTriggerWidth: function(){
        var tw = 0;
        Ext.each(this.triggers, function(t, index){
            var triggerIndex = 'Trigger' + (index + 1),
                w = t.getWidth();
            if(w === 0 && !this['hidden' + triggerIndex]){
                tw += this.defaultTriggerWidth;
            }else{
                tw += w;
            }
        }, this);
        return tw;
    },

    // private
    onDestroy : function() {
        Ext.destroy(this.triggers);
        AIR2.Search.Inquiry.PickerBox.superclass.onDestroy.call(this);
    },

    onTrigger1Click  : function() {
        this.onTriggerClick();
    },

    onTrigger2Click : function(){
        // remove the Box (and any children) from the parent
        this.removeFromParent();
    }

});

